import React, { useEffect, useState } from 'react';
import { Drawer, message, Spin, Tooltip } from 'antd';
import { useSetState } from 'ahooks';
import { features, useTablePipeline } from 'ali-react-table';
import { AntdBaseTable } from '@/base/TBaseTable';
import moment from 'moment';
// @ts-ignore
import { CheckCircleOutlined, CloseCircleOutlined } from '#/utils/antdIcons';
import { TRDefault } from '@/components/index.js';
import { HttpCode } from '#/utils/contacts.js';
import { DrawerHeader, ExplainTitle } from '../index';
import planIcon from '@/assets/img/plan_icon.png';
import type {
  IAdjustPolicyEditingSourceDataListType,
  IAllIssuePlanListDataType,
  IAllIssuePlanListType,
  IDealElementOptions,
  IOptionType,
  IOrginDealElementOptions,
  IPostQueryAllIssuePlanListParamsType,
  IStationsData,
} from '../../type';
import { ITitleType } from '../../type';
import { getAllDealElementOptions } from '../../tool';
import {
  postNewQueryAllIssuePlanList,
  postNewQueryDataSourceList,
  postQueryAllIssuePlanList,
  postQueryDataSourceList,
} from '../../service';
import {
  new_ExecuteStatusOptions,
  statusFirstOptions,
  statusFirstSelOptions,
  statusLastOptions,
  statusLastSelOptions,
  statusSecondOptions,
  statusSecondSelOptions,
  titleMap,
} from '../../dictionary';
import styles from './index.less';
import _ from 'lodash';

interface IProps {
  /**
   * 省份数据
   */
  provinceOptions?: IDealElementOptions[];
  /**
   * 是否显示抽屉
   */
  visible?: boolean;
  /**
   * 关闭函数
   */
  onClose?: () => void;
}

const AllIssuePlan = (props: IProps) => {
  const { visible = false, onClose, provinceOptions } = props;
  const [formValue, setFormValue] = useSetState<IPostQueryAllIssuePlanListParamsType>({});
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [isError, setIsError] = useState<boolean>(false);
  const [stationData, setStationData] = useSetState<IStationsData>({
    dealElementOptions: [],
    dealElementModalOptions: [],
    dealElementDataObj: {},
  }); // 交易单元列表
  const [dataSourceOptions, setDataSourceOptions] = useState<IOptionType[]>();
  const [allIssuePlanList, setAllIssuePlanList] = useState<IAllIssuePlanListType[]>([]);

  // 处理全部交易单元
  const getStationList = (data: IOrginDealElementOptions[]): IStationsData => {
    const _dealElementResultData = getAllDealElementOptions(data || []);
    const _data: IStationsData = {
      dealElementOptions: _dealElementResultData?.value || [],
      // @ts-ignore
      dealElementModalOptions: _dealElementResultData?.modalData || [],
      dealElementDataObj: _dealElementResultData.dataObj,
    };
    return _data;
  };

  // 查询交易单元关联的所有数据源
  const getDataSourceList = async (params: { stationList: string[] }) => {
    const res1StationList: any = [];
    const res2StationList: any = [];
    // 山西和甘肃得场站走新接口
    params?.stationList?.forEach((i) => {
      if (i.startsWith('62') || i.startsWith('14')) {
        res2StationList.push(i);
      } else {
        res1StationList.push(i);
      }
    });
    let _dataSourceOptions = [];
    const queryDataServiceArr: any = [];
    if (res1StationList.length > 0) {
      queryDataServiceArr.push(
        postQueryDataSourceList({
          stationList: res1StationList,
        }),
      );
    }
    if (res2StationList.length > 0) {
      queryDataServiceArr.push(
        postNewQueryDataSourceList({
          stationList: res2StationList,
        }),
      );
    }
    const [res1 = {}, res2 = {}]: any = await Promise.all(queryDataServiceArr);
    let data: any = [];
    if (res1?.statusCode === HttpCode.SUCCESS) {
      data = [...data, ...(res1?.data || [])];
    }
    if (res2?.statusCode === HttpCode.SUCCESS) {
      data = [...data, ...(res2?.data || [])];
    }
    data = _.uniqBy(data, 'dataSourceName');
    _dataSourceOptions = data.map((item: IAdjustPolicyEditingSourceDataListType) => {
      return {
        value: item?.dataSourceId,
        label: item?.dataSourceName,
      };
    });
    setDataSourceOptions(_dataSourceOptions);
    return _dataSourceOptions || [];
  };

  // 处理执行总览列表数据
  const dealAllIssuePlanList = (val: IAllIssuePlanListDataType[]) => {
    const _allIssuePlanList: IAllIssuePlanListType[] = [];
    val.forEach((itemOne, indexOne: number) => {
      itemOne?.provinceIssuePlanList?.forEach((itemTwo, indexTwo: number) => {
        itemTwo?.stationIssuePlanList?.forEach((item) => {
          _allIssuePlanList.push({
            ...item,
            issueDate: itemOne?.issueDate,
            provinceName: itemTwo?.provinceName,
            provinceIndex: `${indexOne}${itemTwo?.provinceName}`,
            stationIndex: `${indexOne}${indexTwo}${item?.stationName}`,
          });
        });
      });
    });
    setAllIssuePlanList(_allIssuePlanList);
  };

  // 合并新老接口得数据
  const mergeData = (arr1: any, arr2: any) => {
    arr2.forEach((i: any) => {
      const index = arr1.findIndex((j: any) => j.issueDate === i.issueDate);
      if (index !== -1) {
        arr1[index].provinceIssuePlanList.push(...i.provinceIssuePlanList);
      } else {
        arr1.push(i);
      }
    });
    return arr1.sort((a: any, b: any) => {
      return moment(a.issueDate).isBefore(moment(b.issueDate)) ? 1 : -1;
    });
  };

  // 查询执行总览列表
  const getAllIssuePlanList = async (params: IPostQueryAllIssuePlanListParamsType) => {
    setIsLoading(true);
    setIsError(false);
    const res1StationList: any = [];
    const res2StationList: any = [];
    const queryDataServiceArr: any = [];
    // 山西和甘肃得场站走新接口
    params?.stationList?.forEach((i) => {
      if (i.startsWith('62') || i.startsWith('14')) {
        res2StationList.push(i);
      } else {
        res1StationList.push(i);
      }
    });
    if (res1StationList.length > 0) {
      queryDataServiceArr.push(
        postQueryAllIssuePlanList({
          ...params,
          stationList: res1StationList,
        }),
      );
    }
    if (res2StationList.length > 0) {
      queryDataServiceArr.push(
        postNewQueryAllIssuePlanList({
          ...params,
          stationList: res2StationList,
        }),
      );
    }
    const [res1 = {}, res2 = {}]: any = await Promise.all(queryDataServiceArr);
    let data1: any = [];
    let data2: any = [];
    if (res1?.statusCode === HttpCode.SUCCESS) {
      data1 = res1?.data || [];
    }
    if (res2?.statusCode === HttpCode.SUCCESS) {
      data2 = res2?.data || [];
    }
    const data = mergeData(data1, data2);
    dealAllIssuePlanList(data);
    setIsLoading(false);
  };

  // 搜索数据
  const onSearch = async (params: IPostQueryAllIssuePlanListParamsType) => {
    const _params = {
      ...params,
      dataSourceList: params?.dataSourceList?.flat(),
    };
    await getAllIssuePlanList(_params);
    setFormValue(params);
  };

  // 取消
  const _onCancel = () => {
    onClose && onClose();
  };

  // 改变交易单元
  const onChangeStation = async (val: IPostQueryAllIssuePlanListParamsType) => {
    if (val) {
      const _dataSourceOptions = await getDataSourceList({ stationList: val?.stationList || [] });
      const _dataSourceList = (_dataSourceOptions || []).map(
        (item: IOptionType) => item?.value || '',
      );
      const _params = {
        ...val,
        dataSourceList: _dataSourceList,
      };
      setFormValue(_params);
    }
  };

  const fetchData = async () => {
    const _stationData = getStationList(provinceOptions || []);
    const _stationList = (_stationData?.dealElementOptions || []).map(
      (item: IDealElementOptions) => item?.value || '',
    );
    const _dataSourceOptions = await getDataSourceList({ stationList: _stationList });
    const _dataSourceList = (_dataSourceOptions || []).map(
      (item: IOptionType) => item?.value || '',
    );
    const _params = {
      stationList: _stationList,
      dataSourceList: _dataSourceList,
      startDate: moment().subtract(6, 'days').format('YYYY-MM-DD'),
      endDate: moment().format('YYYY-MM-DD'),
      statusFirst: statusFirstSelOptions.map((item) => item.value),
      statusSecond: statusSecondSelOptions.map((item) => item.value),
      statusLast: statusLastSelOptions.map((item) => item.value),
    };
    onSearch(_params as any);
    setStationData(_stationData);
  };

  useEffect(() => {
    if (visible) {
      fetchData();
    }
  }, [visible]);

  const executeStatusTitle = (type: ITitleType) => {
    return (
      <div className={styles.executeStatusTitle}>
        <ExplainTitle title={titleMap[type].title} hintText={titleMap[type].hintText} />
      </div>
    );
  };

  const columns = [
    {
      code: 'issueDate',
      name: '申报执行日期',
      width: 120,
      align: 'center',
      features: { autoRowSpan: true, sortable: true },
      render(v: string) {
        return v ? moment(v).format('YYYYMMDD') : '-';
      },
    },
    {
      code: 'provinceIndex',
      name: '省份',
      features: { autoRowSpan: true, sortable: true },
      width: 150,
      align: 'center',
      render(v: string, records: IAllIssuePlanListType) {
        return (
          <div className={styles.reason}>
            <Tooltip placement="topLeft" title={records?.provinceName}>
              {records?.provinceName || '-'}
            </Tooltip>
          </div>
        );
      },
    },
    {
      code: 'stationIndex',
      name: '交易单元',
      lock: true,
      width: 160,
      align: 'center',
      features: { autoRowSpan: true, sortable: true },
      render(v: string, records: IAllIssuePlanListType) {
        return (
          <div className={styles.reason}>
            <Tooltip placement="topLeft" title={records?.stationName}>
              {records?.stationName || '-'}
            </Tooltip>
          </div>
        );
      },
    },
    {
      code: 'dataSourceName',
      name: '下发主站',
      width: 120,
      align: 'center',
      render(v: string) {
        return (
          <div className={styles.reason}>
            <Tooltip placement="topLeft" title={v}>
              {v || '-'}
            </Tooltip>
          </div>
        );
      },
    },
    {
      code: 'issueTime',
      name: '任务执行时间',
      width: 120,
      align: 'center',
      render(v: string) {
        return v ? moment(`${moment().format('YYYY-MM-DD')} ${v}`).format('HH:mm') : '-';
      },
    },
    {
      code: 'executeStatus',
      name: executeStatusTitle(ITitleType.STATUS_EXECUTE),
      dataIndex: 'executeStatus',
      // title: '执行状态',
      width: 150,
      align: 'center',
      render(v: string, record: any) {
        const _data = new_ExecuteStatusOptions.find((item) => item.value === v);
        return _data ? (
          <div className={styles.executeStatus}>
            <div className={`${styles.status_box} ${styles[_data.class]}`}>{_data.label}</div>
            {_data.detail ? (
              <Tooltip placement="bottomLeft" title={record.statusReason}>
                <div style={{ color: 'var(--bd-primary)', height: 20, width: 50 }}>详情</div>
              </Tooltip>
            ) : (
              ''
            )}
          </div>
        ) : (
          '-'
        );
      },
    },
    {
      code: 'statusFirst',
      name: executeStatusTitle(ITitleType.STATUS_FIRST),
      width: 150,
      align: 'center',
      render(v: string) {
        const _data = statusFirstOptions.find((item) => item.value === v);
        return _data ? (
          <div className={styles.statusLast}>
            <div className={`${styles.status_box} ${styles[_data.class]}`}>{_data.label}</div>
          </div>
        ) : (
          '-'
        );
      },
    },
    {
      code: 'statusSecond',
      name: executeStatusTitle(ITitleType.STATUS_SECOND),
      width: 150,
      align: 'center',
      render(v: string) {
        const _data = statusSecondOptions.find((item) => item.value === v);
        return _data ? (
          <div className={styles.statusLast}>
            <div className={`${styles.status_box} ${styles[_data.class]}`}>{_data.label}</div>
          </div>
        ) : (
          '-'
        );
      },
    },
    {
      code: 'statusLast',
      name: executeStatusTitle(ITitleType.STATUS_LAST),
      width: 150,
      align: 'center',
      render(v: string) {
        const _data = statusLastOptions.find((item) => item.value === v);
        return _data ? (
          <div className={styles.statusLast}>
            <div className={`${styles.status_box} ${styles[_data.class]}`}>{_data.label}</div>
          </div>
        ) : (
          '-'
        );
      },
    },
    {
      code: 'operationUser',
      name: '策略编辑人',
      width: 100,
      align: 'center',
      render(v: string) {
        return v ? v : '-';
      },
    },
  ];

  const pipeline = useTablePipeline()
    .input({ dataSource: allIssuePlanList, columns: columns as any })
    .primaryKey('id')
    .use(features.autoRowSpan())
    .appendRowPropsGetter((): any => {
      const color = '#222629';
      return {
        style: { '--bgcolor': color, '--hover-bgcolor': color },
      };
    });

  return (
    <Drawer
      width={1400}
      className={styles.operateLogModal}
      visible={visible}
      onClose={_onCancel}
      title={
        <div className={styles.titleDiv}>
          <img src={planIcon} className={styles.titleLogo} />
          <span className={styles.title}>申报总览</span>
        </div>
      }
      footer={null}
    >
      <div className={styles.container}>
        <div className={styles.header}>
          <DrawerHeader
            values={formValue}
            dataSourceOptions={dataSourceOptions}
            stationData={stationData}
            onSearch={onSearch}
            onChangeStation={onChangeStation}
          />
        </div>
        <div className={styles.center}>
          {isLoading ? (
            <Spin />
          ) : isError ? (
            <TRDefault type={'emptysm'} message={'系统异常'} />
          ) : allIssuePlanList.length ? (
            <div className={styles.list}>
              <div className={styles.antdBaseTable}>
                <AntdBaseTable
                  useVirtual={{ horizontal: true, vertical: true, header: false }}
                  style={{
                    '--row-height': '28px',
                    // '--header-bgcolor': '#383C3E',
                    '--header-row-height': '28px',
                    '--cell-padding': '4px 16px',
                    '--cell-border-vertical': '1px solid #4E5154',
                    '--header-cell-border-vertical': '1px solid #4E5154',
                    '--hover-bgcolor': '#222629',
                  }}
                  {...pipeline.getProps()}
                />
              </div>
            </div>
          ) : (
            <TRDefault type={'emptysm'} message={'暂无数据'} />
          )}
        </div>
      </div>
    </Drawer>
  );
};

export default AllIssuePlan;
